<template>
    <div class="operationBasicsDetail">

    <div class="header">
     
     <van-nav-bar title="编辑供应商" left-text="" left-arrow @click-left="goBack" />
   </div>
    <div class="add_supplier">
        <van-form @submit="onSubmit" validate-first scroll-to-error>
            <van-cell-group inset>
                <van-field name="recruiterDept" label="合作部门" v-model="queryParams.recruiterDept" readonly disabled
                    input-align="right" error-message-align="right" placeholder="请选择" />
                <van-popup v-model:show="showRecruiterDept" position="bottom">
                    <van-picker :columns="recruiterDeptColumns" @confirm="onConfirmRecruiterDept"
                        @cancel="showRecruiterDept = false" />
                </van-popup>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="recruiter" label="合作人员" v-model="queryParams.recruiter" readonly disabled
                    input-align="right" error-message-align="right" placeholder="请选择" />
                <van-popup v-model:show="showRecruiter" position="bottom">
                    <van-picker :columns="recruiterColumns" @confirm="onConfirmRecruiter"
                        @cancel="showRecruiter = false" />
                </van-popup>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="supplierName" label="供应商名称" v-model="queryParams.supplierName" placeholder="请输入供应商名称"
                    maxlength="20" input-align="right" error-message-align="right" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入供应商名称' },
                        {
                            validator: validatorNumbers,
                            message: '请输入正确的供应商名称',
                        },
                    ]" >
                         
                </van-field>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="supplierType" label="供应商类型" v-model="queryParams.supplierType"  readonly
                    placeholder="请选择供应商类型" @click="showSupplierType = true" input-align="right" error-message-align="right"
                    required :rules="[
                        { required: true, trigger: 'onBlur', message: '请选择贸易方式' },
                    ]" >
                     <template #right-icon>
                        <van-icon name="arrow" size="3.733333vw" color="#B9BABB"/>
                    </template> 
                </van-field>
                <van-popup v-model:show="showSupplierType" position="bottom">
                    <van-picker :columns="supplierTypeColumns" @confirm="onConfirmSupplierType"
                        @cancel="showSupplierType = false" v-model="supplierType" />
                </van-popup>
            </van-cell-group>
            
            <van-cell-group inset>
                <van-field name="contactName" label="联系人" v-model="queryParams.contactName" placeholder="请输入联系人姓名"
                    input-align="right" error-message-align="right" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入联系人' },
                        { validator: validatorContact, message: '请输入中文或点·' },
                    ]" />
            </van-cell-group>
            <formNumberKeyboard :formRef="formRef" name="phone" label="联系电话" input-align="right"
                error-message-align="right" v-model:keyValue="queryParams.phone" placeholder="请输入联系电话" required readonly
                :rules="[
                    { required: true, trigger: 'onBlur', message: '请输入联系电话' },
                    { validator: validatorPhone, message: '请输入正确电话' },
                ]" />
            <van-cell-group inset>
                <van-field v-model="queryParams.addr" readonly name="addr" label="厂家地址" placeholder="点击选择省市区"
                    input-align="right" error-message-align="right" @click="showAddress = true" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请选择厂家地址' },
                    ]" >
                    <template #right-icon>
                        <van-icon name="arrow" size="3.733333vw" color="#B9BABB"/>
                    </template> 
                </van-field>
                <van-popup v-model:show="showAddress" position="bottom">
                    <van-area :area-list="areaList" @confirm="onConfirmAddress" @cancel="showAddress = false"
                        v-model="addr" />
                </van-popup>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="address" label="详细地址" v-model="queryParams.address" placeholder="请输入详细地址" maxlength="100"
                    input-align="right" error-message-align="right" required
                    @input="(e) => { forbidRule(e, 'address', 'emoji') }" :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入详细地址' }
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field input-align="right" name="storeId" error-message-align="right" label="店铺ID"
                    v-model="queryParams.storeId" placeholder="请输入快手ID" :maxlength="50" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field input-align="right" name="storeType" error-message-align="right" label="店铺类型"
                    v-model="queryParams.storeType" placeholder="请输入快手店铺类型" :maxlength="50" :rules="[
                        {
                            validator: validatorStoreType,
                            message: '只能输入中文',
                        },
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field input-align="right" name="storeGrade" error-message-align="right" label="店铺评分"
                    v-model="queryParams.storeGrade" placeholder="请输入快手店铺评分" :rules="[
                        {
                            validator: validatorStoreGrade,
                            trigger: 'onChange',
                            message: '0-100内数字，最大小数点后两位',
                        },
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="companyCode" label="统一社会信用代码" input-align="right" error-message-align="right"
                    v-model="queryParams.companyCode" placeholder="请输入统一社会信用代码" :rules="[
                        {
                            validator: validatorCompanyCode,
                            message: '请输入正确统一社会信用代码',
                        },
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field v-model="queryParams.businessAddr"  readonly input-align="right"
                    error-message-align="right" name="businessAddr" label="营业执照所在地" placeholder="点击选择省市区"
                    @click="showBusinessAddress = true" >
                    <template #right-icon>
                        <van-icon name="arrow" size="3.733333vw" color="#B9BABB"/>
                    </template>   
                </van-field>
                <van-popup v-model:show="showBusinessAddress" position="bottom">
                    <van-area title="营业执照所在地" :area-list="areaList" @confirm="onConfirmBusinessAddress"
                        @cancel="showBusinessAddress = false" v-model="businessAddr" />
                </van-popup>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="businessDate" label="营业执照有效期" input-align="right" error-message-align="right"
                    v-model="queryParams.businessDate"  readonly placeholder="请选择"
                    @click="showBusinessDate = true" >
                    <template #right-icon>
                        <van-icon name="arrow" size="3.733333vw" color="#B9BABB"/>
                    </template>  
                </van-field>
                <van-popup v-model:show="showBusinessDate" position="bottom">
                    <van-picker title="营业执照有效期" active-class="showSupplierType-style" :show-toolbar="true"
                        :columns="businessDateColumns" @confirm="onConfirmBusinessDate"
                        @cancel="showBusinessDate = false" v-model="businessDate" />
                </van-popup>
            </van-cell-group>
            <div class="image-title">
                营业执照
            </div>
            <van-cell-group class="imgform" inset>
                <van-field name="营业执照" label="" v-model="queryParams.businessImage">
                    <template #input>
                        <UpLoadDom :arr="businessImageList || []" @deleteClick="deleteImg"  width="90"
                            height="90" @postImageClick="postImage('businessImage', 1)" :max-count="1"
                            :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="image-title">
                其他资质
            </div>
            <van-cell-group class="imgform" inset>
                <van-field name="其他资质" label="" v-model="queryParams.otherImage">
                    <template #input>
                        <UpLoadDom :arr="otherImageList || []" @deleteClick="deleteImg" width="90"
                            height="90" @postImageClick="postImage('otherImage', 5)" :max-count="5" :isPdfLook="true" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="addtive_div-btn">
                <div class="addtive_div">
                    <van-button round block :loading="loading" loading-text="执行中..." type="primary" native-type="submit"
                        v-throttle:click>
                        保存
                    </van-button>
                </div>
            </div>
        </van-form>
    </div>
    </div>
</template>
<script setup lang="ts">
import { getDicts, getUserById } from "@/api/productList/index";
import { areaList } from "@vant/area-data";
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { hmSupplierList, updateHmSupplier } from "@/api/supplierList/index";
import { showSuccessToast, showFailToast } from "vant";
import { getEnvValue } from "@/utils";
import { storeToRefs } from "pinia";
import { loginStore } from "@/store/login";
import formNumberKeyboard from '@/components/formNumberKeyboard/index.vue'
import { handleImageUpdate } from "@/utils/handleImageUpdate";
import UpLoadDom from '@/components/isImgPdf/upLoadDom.vue'
const store = loginStore();
const { token } = storeToRefs(store);
const formRef = ref()

const loading = ref(false)
const queryParams = ref({
    supplierName: "",
    supplierType: "",
    addr: "",
    address: "",
    contactName: "",
    phone: "",
    recruiterDept: "",
    recruiter: "",
    companyCode: "",
    businessAddr: "",
    businessDate: "",
    businessImage: "",
    storeId: "",
    storeType: "",
    storeGrade: "",
    otherImage: "",
});
const supplierType = ref<any[]>([]);
const businessDate = ref<any[]>([]);
const addr = ref("");
const businessAddr = ref("");
const showBusinessDate = ref(false);
const businessDateColumns = ref([
    {
        text: "1年",
        value: "1",
    },
    {
        text: "10年",
        value: "10",
    },
    {
        text: "20年",
        value: "20",
    },
    {
        text: "长期",
        value: "0",
    },
]);

const router = useRouter();
const showSupplierType = ref(false);
const supplierTypeColumns = ref([]);
const showAddress = ref(false);
const showRecruiterDept = ref();
const recruiterDeptColumns = ref([]);
const showRecruiter = ref(false);
const recruiterColumns = ref([]);

// 输入事件、禁用规则
const forbidRule = (e: any, key: string, type: string) => {
    // 输入法表情默认不能输入
    if (type == 'emoji') {
        // emoji：输入时禁用输入法表情
        queryParams.value[key] = e.target.value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    } else if (type == 'blank') {
        // blank：输入时禁用空格
        queryParams.value[key] = e.target.value.replace(/\s|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    }
}
const validatorPhone = (val) => {
    if (val && val.length >= 11) {
        return /^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(val);
    } else {
        return true
    }
}
const validatorNumbers = (val) => /^[\u0020-\u007e\u4e00-\u9fa5]+$/.test(val);
const businessImageList = ref<any[]>([]);
const otherImageList = ref<any[]>([]);
const validatorCompanyCode = (val) => {
    if (val) {
        return /^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/.test(
            val
        );
    } else {
        return true;
    }
};
// 店铺类型验证，只能输入中文
const validatorStoreType = (val) => {
    if (val) {
        return /^[\u4e00-\u9fa5]+$/.test(val)
    } else {
        return true
    }
}
// 联系人验证函数，只能输入中文跟·
const validatorContact = (val) => /^[\u4e00-\u9fa5·]+$/.test(val);
// 店铺评分验证函数，0-100之间的整数，保留小数点后两位
const validatorStoreGrade = (val) => {
    if (val) {
        return /^([0-9]{1,2}$)|(^[0-9]{1,2}\.[0-9]{1,2}$)|100$/.test(val);
    } else {
        return true;
    }
};
const showBusinessAddress = ref(false);

const route = useRoute();
/** 商品id */
const uniquekey = computed(() => {
    return route.params.id;
});

/** 获取详情 */
const getDetail = async () => {
    const res = await hmSupplierList({ id: uniquekey.value as any });
    if (res.rows[0].businessImage) {
        businessImageList.value.push({
            url: getEnvValue("VITE_APP_PIC_URL") + res.rows[0].businessImage
        });
    }
    if (res.rows[0].otherImage) {
        res.rows[0].otherImage.split(",").forEach((item: any) => {
            otherImageList.value.push({
                url: getEnvValue("VITE_APP_PIC_URL") + item
            });
        })
    }
    queryParams.value = res.rows[0];
    supplierType.value = [res.rows[0].supplierType];
    businessDate.value = [res.rows[0].businessDate];
    addr.value = res.rows[0].addrValues;
    const recruiterDept: any[] = [];
    const recruiter: any[] = [];
    res.rows[0].extraData.forEach((item: any) => {
        recruiterDept.push(item.recruiterDeptName);
        recruiter.push(item.recruiterName);
    });
    queryParams.value.recruiterDept = recruiterDept.join(" | ");
    queryParams.value.recruiter = recruiter.join(" | ");
};
getDetail();

/** 营业执照所在地关闭 */
const onConfirmBusinessAddress = ({ selectedOptions }) => {
    queryParams.value.businessAddr =
        selectedOptions[0]?.text +
        "-" +
        selectedOptions[1]?.text +
        "-" +
        selectedOptions[2]?.text;
    showBusinessAddress.value = false;
    businessAddr.value = selectedOptions[selectedOptions.length - 1].value;
};
/** 营业执照有效期关闭 */
const onConfirmBusinessDate = ({ selectedOptions }) => {
    queryParams.value.businessDate = selectedOptions[0]?.text;
    showBusinessDate.value = false;
    businessDate.value = [selectedOptions[0]?.text];
};
/** 供应商类型 */
const getSupplierType = async () => {
    const res = await getDicts("hm_supplier_type");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    supplierTypeColumns.value = res.data;
};
getSupplierType();
/** 供应商类型关闭 */
const onConfirmSupplierType = ({ selectedOptions }) => {
    queryParams.value.supplierType = selectedOptions[0]?.text;
    showSupplierType.value = false;
    supplierType.value = [selectedOptions[0]?.text];
};
/** 厂家地址关闭 */
const onConfirmAddress = ({ selectedOptions }) => {
    queryParams.value.addr =
        selectedOptions[0]?.text +
        "-" +
        selectedOptions[1]?.text +
        "-" +
        selectedOptions[2]?.text;
    showAddress.value = false;
    addr.value = selectedOptions[selectedOptions.length - 1].value;
};
const onConfirmRecruiterDept = async ({ selectedOptions }) => {
    // 根据招商部获取招商员
    const res = await getUserById(selectedOptions[0].deptId);
    res.data.forEach((element) => {
        element.text = element.nickName;
        element.value = element.userId;
    });
    recruiterColumns.value = res.data;
    queryParams.value.recruiter = "";

    queryParams.value.recruiterDept = selectedOptions[0]?.text;
    showRecruiterDept.value = false;
};
/** 招商员关闭 */
const onConfirmRecruiter = ({ selectedOptions }) => {
    queryParams.value.recruiter = selectedOptions[0]?.text;
    showRecruiter.value = false;
};
/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
const onSubmit = async () => {
    loading.value = true
    try {
        const data = JSON.parse(JSON.stringify(queryParams.value));
        data.businessImage = getPicByfullPath(businessImageList.value);
        data.otherImage = getPicByfullPath(otherImageList.value);
        delete data.recruiter;
        delete data.recruiterDept;
        await updateHmSupplier({ ...data, addrValues: addr.value });
        loading.value = false
        showSuccessToast({ type: "success", message: "修改供应商成功" });
        router.back();
    } catch (error) {
        if (error == 'timeout') {
            showFailToast('修改供应商失败');
        }
        loading.value = false
    }
};
/** 删除 */
const deleteImg = (list: any, index: number,) => {
    list.splice(index, 1);
};
(window as any).msgFromUniapp = function (arg) {
  const imageLists = {
    businessImage: businessImageList.value,
    otherImage: otherImageList.value
  };

  const maxCounts = {
    businessImage: 1,
    otherImage: 5
  };

  const imageList = imageLists[arg.name];
  const maxCount = maxCounts[arg.name];
  handleImageUpdate(imageList, arg, maxCount);

};
const postImage = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "img",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + "/resource/oss/upload",
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};
/** 返回上一页 */
const goBack = () => {
  router.back()
}
</script>
<style lang="less" scoped>
:deep(.van-field__label) {
    width: 115px;
}

.add_supplier {
    background-color: #F6FAFF;
    width: 100%;
    height: calc(100vh - 90px);
    box-sizing: border-box;
    padding: 10px 15px 94px 15px;
    margin-top: 90px;
    overflow-y: scroll;
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

:deep(.van-form) {
    background-color: #fff;
}

.additive_class {
    position: fixed;
    font-size: 12px;
    left: 50%;
    transform: translateX(-50%);
    bottom: 70px;
    color: #1466ff;
}

:deep(.van-field__control) {
    color: #b8beca !important;
}

:deep(.van-icon-arrow:before) {
    color: #b8beca !important;
}

.value {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;

    .imgList {
        position: relative;

        .loading_pic {
            width: 90px;
            height: 90px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        :deep(.van-image__img) {
            margin-right: 5px;
        }

        :deep(.van-icon) {
            position: absolute;
            top: 0;
            z-index: 100;
            right: 4px;
            font-size: 10px;
            height: 15px;
            width: 15px;
            background-color: #000;
            border-bottom-left-radius: 16px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        :deep(.van-icon-cross:before) {
            margin: 0 0 1px 2px;
        }
    }

    :deep(.van-image__img) {
        width: 77px;
        height: 77px;
    }
}

.addtive_div-btn {
    position: fixed;
    width: 100%;
    height: 84px;
    bottom: 0;
    left: 0;
    z-index: 110;
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    background-color: #fff;
    box-shadow: 0px 0px 8px 0px rgba(189,195,204,0.5);
    box-sizing: border-box;
    padding: 0 15px;
}

.addtive_div {
    width: 100%;
    bottom: 20px;
    text-align: center;
    margin: auto;
    margin-bottom: 20px;
}
.operationBasicsDetail {
  width: 100%;
  // height: 100vh;
  background: #f6faff;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
  justify-content: center;
  align-content: flex-start;

  .header {
    background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
    filter: blur(0px);
    height: 90px;
    padding-top: 44px;
    box-sizing: border-box;
    width: 100%;
    position: fixed;
    z-index: 6003;

    :deep(.van-icon-arrow-left) {
      color: #1a1b1c !important;
    }

    :deep(.van-nav-bar) {
      background: none !important;
    }

    :deep(.van-nav-bar__content) {
      background-color: transparent !important;
    }
  }

}
:deep(.van-cell-group--inset) {
  margin: 0 !important;
  border-radius: 0 !important;
}

:deep(.van-form) {
  // height: 100%;
  // overflow-y: scroll;
  background-color: #fff;
  // padding-bottom: 35px !important;
}
:deep(.van-field--disabled){
  background-color: #f3f3f3;
  .van-field__control{
    color: #8492AD !important;
    -webkit-text-fill-color:#8492AD !important;
  }
  div[aria-checked=true] .van-radio__icon{
    color: #0094FF !important;
    -webkit-text-fill-color: #0094FF !important;
  }
}
:deep(.van-cell) {
      padding: 20px 15px;
      position: relative;
      &::after{
         content: "";
         display: block;
         height: 2px;
         width: 315px;
         background-color: #F3F3FF;
      }
      
      
  }
  :deep(.van-cell-group):last-child{

      .van-cell{
          border-bottom: none !important;
      }
      
  }
  :deep(.van-field__label) {
    
      color: #464E5D  !important;
  }

  :deep(.van-field__label--required){
      &::before{
          display: none;
      }
      &::after{
          color: var(--van-field-required-mark-color);
          content: "*";
      }
  }
  .imgform{
    :deep(.van-cell) {
        border-bottom: none !important;
        &::after{
            content: none;
        }
    }
  }
  .image-title {
    font-weight: 400;
    font-size: 14px;
    color: #1a1b1c;
    background-color: #fff;
    padding-left: 16px;
    margin-top: 20px;
  }
</style>